define(['app', 'angularAMD', 'fastClick'], function (app, angularAMD, FastClick) {
    'use strict';
    function getURLParam(){
        var url_object = {
            protocol:window.location.protocol,
            host:window.location.hostname,
            port : window.location.port,
        };
        var temp = window.location.href.split('index.html?');
        if(temp.length>1){
            temp = temp[temp.length-1].split('#/')[0].split('&');
            temp.forEach(function(item){
                var item_array = item.split('=');
                if(item_array.length == 2){
                    url_object[item_array[0]] = item_array[1];
                }
            });
        }
        return url_object;
    }
	app.config(['$translateProvider', '$compileProvider', 'config',
        function($translateProvider, $compileProvider, config) {
            try{
                if (localStorage != undefined) {
                    //Load common config from localstorage[SMES_setting]
                    config.setting = angular.merge(config.setting, JSON.parse(localStorage.getItem(config.appName + '_setting')));
                    if(!config.setting.fullScreen){
                        config.setting.fullScreen = 'Y';
                    }
                    if(!config.setting.virtualKeyboard){
                        config.setting.virtualKeyboard = 'N';
                    }

                    //語系設定
                    var _langList = localStorage.getItem(config.appName + '_langList');
                    if (_langList) {
                        config.langList = JSON.parse(_langList);
                    }

                    //20190827 modify by Dustdusk for M#: 當使用http://進入時，自動抓取ip/port
                    var _url = window.location.href||'';
                    if(_url.indexOf('http://') == 0){
                        if(_url.indexOf('Production') != -1){
                            config.setting.environment = 'Production';
                        } else
                            config.setting.environment = 'Test';

                        //Get default Server info in config.json
                        config.server = angular.merge({}, config.serverList[config.setting.environment]);
                        config.server.use_web = true;
                        var _start = _url.indexOf('http://')+7;
                        var _middle = _url.indexOf(':', _start);
                        var _end = _url.indexOf('/', _start);
                        if(_middle == -1){
                            config.server.ip = _url.substring(_start, _end);
                            config.server.port = 80;
                        } else {
                            config.server.ip = _url.substring(_start, _middle);
                            config.server.port = _url.substring(_middle+1, _end);
                        }

                        if(config.server.ip == 'localhost')
                            config.server.ip = '127.0.0.1';
                    } else {
                        //Get default Server info in config.json
                        config.server = angular.merge({}, config.serverList[config.setting.environment]);

                        //Load server config from localstorage[SMES_server]、localstorage[SMES_login]、URL Paraments
                        var LocalServerConfig = JSON.parse(localStorage.getItem(config.appName + '_server')||'{}');

                        if(LocalServerConfig.ip != undefined){
                            config.server.ip = LocalServerConfig.ip;
                            config.server.port = LocalServerConfig.port;
                            config.server.timeout = LocalServerConfig.timeout;
                        }
                    }

                    var url_paramt = getURLParam(),
                        login_string = localStorage.getItem(config.appName + '_login');
                    if(url_paramt.user_no && url_paramt.user_password){
                        config.login ={};
                        config.login.account = url_paramt.user_no;
                        config.login.password = url_paramt.user_password;
                        config.login.session = url_paramt.session;
                        config.login.program = url_paramt.program;
                        config.login.program_name = url_paramt.program_name;
                    } else if(login_string){
                        config.login = JSON.parse(login_string);
                    } else {
                        config.login = undefined;
                    }
                }
                // Localization Config
				var localizationSettings= [];
				for(var index in config.module){
					localizationSettings.push({
						prefix: 'module/'+config.module[index].name+'/localization/localization-',
						suffix: '.json'
					});
				}
                $translateProvider.useStaticFilesLoader({files:localizationSettings});
                $translateProvider.preferredLanguage(config.setting.lang);

                //Avoid mobile devices click event 300ms delay
                FastClick.attach(document.body);

                if(window.nodeRequire){
                    //取得IP / MAC 資訊
                    var net_interface = window.nodeRequire('os').networkInterfaces();
                    for (var net_name in net_interface) {
                        for (var index in net_interface[net_name]) {
                            var address = net_interface[net_name][index];
                            if (address.family === 'IPv4' && !address.internal) {
                                config.cache.ip = address.address;
                                //20200313 modify by Dustdusk for M#: 修正MAC，保持與後台一致
                                config.cache.mac = address.mac.replace(/:/g, '').toUpperCase();
                                break;
                            }
                        }
                    }
                    try{
                        window.nodeRequire('nw.gui')
                        $compileProvider.imgSrcSanitizationWhitelist(/^\s*((https?|ftp|file|blob|chrome-extension):|data:image\/)/);
                        $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|tel|file|chrome-extension):/);
                    }catch(e){}
                } else if (window.cordova){
                    try{
                        //Use uuid as mac in mobile devices
                        config.cache.mac = window.device.uuid;

                        //Use packageName in mobile devices
                        cordova.getAppVersion.getPackageName().then(function(packageName){
                            config.packageName = packageName;
                        });

                        //Set full screen in mobile Devices
                        window.AndroidFullScreen.immersiveMode(function (){
                            //console.info('It worked!');
                        }, function (error){
                            alert(error);
                        });

                        //Hide status bar in mobile devices
                        window.StatusBar.hide();

                        //Disable backbutton in Android
                        document.addEventListener('backbutton', function onBackKeyDown(e) {
                            e.preventDefault();
                        }, false);

                        //Fix Screen when Keyboard shown in iDevices
                        cordova.plugins.Keyboard.disableScroll(true);
                        window.navigationbar.setUp(true);
                        window.addEventListener('native.keyboardhide', function(){
                            try{
                                window.navigationbar.hide();
                            }catch(e){}
                        });
                    }catch(e){
                        console.error(e);
                    }
                    // 20220929 modify by Alan for#118600 : 增加支援ios檔案路徑
                    try{
                        $compileProvider.imgSrcSanitizationWhitelist(/^\s*((https?|ftp|file|blob|chrome-extension|appfile):|data:image\/)/);
                        $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|tel|file|chrome-extension|appfile):/);
                    // 20220930 modify by Alan for#118600 : 修正語法
                    } catch(e) {
                        console.error(e);
                    }
                }
            }catch(e){
                console.error(e);
            }
        }
    ]).config(['$stateProvider', '$urlRouterProvider', 'config',  function($stateProvider, $urlRouterProvider, config) {
        // Don't sync the url till we're ready
        $urlRouterProvider.deferIntercept();
        var default_program = '/login';
        angular.forEach(config.program ,function(value){
            if(value.url){
                var state = angularAMD.route(value);
                if(state.default == true){
                    default_program = value.url;
                }
                $stateProvider.state(value.name, state);
            }
        });
        if(config.login){
            if(config.cache.device == 'phone'){
                $urlRouterProvider.otherwise('/menu');
            } else {
                $urlRouterProvider.otherwise('/home');
            }
        } else {
            $urlRouterProvider.otherwise(default_program);
        }
    }]).run(['$urlRouter', '$rootScope', '$state', '$css', 'config', '$mdDialog', 'RouterExtendProvider',
    function($urlRouter, $rootScope, $state, $css, config, $mdDialog, $RouterExtendProvider){
        $urlRouter.sync();
        $urlRouter.listen();
        if(window.nodeRequire)
            $css.add('JSplugins/angular-material-lite/angular-material-lite-desktop.css');

        if(config.cache.device == 'phone'){
            $RouterExtendProvider.home_page = 'menu';
        } else {
            $RouterExtendProvider.home_page = 'home';
        }

        //20200910 modify by Dustdusk for M#: 調整返回功能
        //Disable backbutton in Android
        document.addEventListener('backbutton', function onBackKeyDown(e) {
            //e.preventDefault();
            if(!$mdDialog.isShow() && $rootScope.Loading.disabled){
                if(typeof $state.$current.locals['@'].$scope.back === 'function'){
                    $state.$current.locals['@'].$scope.back();
                } else if(typeof $state.$current.locals['@'].$scope.back === 'function'){
                    $state.$current.locals['@'].$scope.back();
                }
            } else {
                e.preventDefault();
            }
        }, false);
    }]);
});
